from django.http import JsonResponse
from django.views import View
import re,random,logging
logger = logging.getLogger('django')
from django_redis import get_redis_connection



class SMSCodeView(View):
    # 获取参数
    def get(self,request,mobile):
        if not re.match('1[3-9]\d{9}',mobile):
            return JsonResponse({
                'errno':4004,
                'errmsg':'mobile格式有误'
            })

        # 随机生成短信
        sms_code = "%06d" % random.randint(0,999999)

        # 打印到终端
        logger.info(sms_code)

        # 链接到redis
        conn = get_redis_connection('verify_code')

        # 保存到redis
        conn.setex('sms_code_%s'%mobile,300,sms_code)

        return JsonResponse({
            'errno':0,
            'success':'True',
            'sms_code':sms_code,
            'message':f'短信验证码，测试阶段使用：{sms_code}'
        })


